import java.sql.*;

public class Test {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");//反射
        //数据库连接
        String url = "jdbc:mysql://localhost:3306/test2104";
        String username = "root";
        String password = "root";
        //得到连接对象
        Connection cn = DriverManager.getConnection(url,username,password);

        String sql = "select * from students";
        //创建语句对象
        Statement stat = cn.createStatement();
        //执行查询语句
        ResultSet resultSet = stat.executeQuery(sql);

        //打印数据库表元数据,列名 即students表的字段数
        int cols = resultSet.getMetaData().getColumnCount();
        //数据库返回对象,起始值为1
        for(int i=1;i<=cols;i++){
            System.out.print(i+"."+"   ");
            System.out.print(resultSet.getMetaData().getColumnName(i)+"\t");// \转义字符,\t表示tab键
        }
        System.out.println();
        //打印表中数据
        while (resultSet.next()){//每次调用返回下一条记录,直到遍历结束
            for(int i=1;i<=cols;i++){
                System.out.print("|   ");
                System.out.print(resultSet.getMetaData().getColumnName(i)+"\t");
                System.out.print(resultSet.getString(i)+"\t");// 每遍历列,+tab键使指针落在同行上的又一列
            }
            System.out.println();
        }
        resultSet.close();
        stat.close();
        cn.close();
    }
}
